/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-12-18 16:04:17
 * @filename : controller/aol_spam_by_site.js
 * @version : 
 * @description : 
 */


define(function(require, exports, module){
        
    require("pagination/jquery.pagination"); 
    require("pagination/pagination.css");
    require("artDialog/dist/dialog-min.js"); 
    require("artDialog/css/ui-dialog.css"); 

 
    var name = 'AOL Spam By Site', mId = 'aol_spam_by_site',
        tpl = require('{view}page_email.tpl'),
        tplD = require('{view}page_email_desc.tpl'),
        tplH = require('{view}page_email_head.tpl'),
        tplT = require('{view}table.tpl'),
        tplS = require('{view}select.tpl');

    var tempOpt = {
        engine : 19,
        begin_date : null,
        end_date : null,
        page : 1,
        offset : 13  
    };

    var AOLSpamBSView = Backbone.View.extend({

        initialize: function (obj) { 
            this.run(obj);
        },

        run : function(obj) {
            if ($('.main').length !== 3) { 
                Backbone.routerObj.navigate('index/w/'+mId, { trigger: true });return;
            } else {
                this.tplRender();
            }
        },

        tplRender : function() {
            if ($('#'+mId).length < 1) { 
                $('#index_right').append(_.template(tpl)({obj:{name:name,mId:mId}}));
                $('#'+mId).find('.m_head').append(_.template(tplH));
                this.defaultOpt();
                this.afterBindEvt();
                this.fetchData(tempOpt); 
            } else {
                $('#'+mId).css('display','block');
            } 
        },

        afterBindEvt : function() {
            var tthis = this,dom = $('#'+mId);

            new Pikaday({
                field: dom.find('.from_time')[0],
                firstDay: 1,
                minDate: new Date('1997-01-01'),
                maxDate: new Date('2020-12-31'),
                yearRange: [1997,2020]
            });

            new Pikaday({
                field: dom.find('.to_time')[0],
                firstDay: 1,
                minDate: new Date('1997-01-01'),
                maxDate: new Date('2020-12-31'),
                yearRange: [1997,2020]
            });

            dom.find('.selectTime').on('change',function(){
            var val = $(this).val();
                share.setInputDate(val,mId);
            });

            dom.find('.do').on('click',function(){
                var obj = tthis.getPostData(); 
                if (obj) { 
                    tthis.fetchData(obj);
                }
            });

            dom.find('.m_head').find('input[type="text"]').on('focus',function(){
                $('#'+mId).find('.selectTime').find("option[value='']").attr("selected",true); 
            });

            dom.on('click',function(e){
                var dom = $(e.target);
                if (dom.hasClass('table_text')) {
                    var tr = dom.parents('tr'),
                        user_id = parseInt(tr.find('td').eq(1).find('a').html());
                    var data = _.clone(tempOpt);
                    data.usr_id = user_id;
                    data.offset = 1000;
                    data.page = 1;
                    tthis.fetchDataUserEmail(data);
                }

                if (dom.hasClass('REPORT_USR_ID')) {
                    var tr = dom.parents('tr'),
                        siteName = tr.find('td').eq(0).html();
                        user_id = parseInt(tr.find('td').eq(1).find('a').html()),
                        siteAllName = share.getSiteAllName($.trim(siteName));
                        window.open("http://www."+siteAllName+"/censor_show?prof_id="+user_id);   
                }

            });
        },

        openDialog : function(content) {
              var d = dialog({
                    title: 'Email Title List',
                    content: content,
                    width:650
              });
              d.showModal();
        },

        defaultOpt : function() {
             var dom = $('#'+mId);
             this.selectSite();
             share.setInputDate('last-week',mId);
             tempOpt.end_date = dom.find('.to_time').val();
             tempOpt.begin_date = dom.find('.from_time').val(); 
             tempOpt.engine  = '19';
        },
 
        selectSite : function() {
             var siteInfo = share.getAllSites();
             $('#'+mId).find('.selectInfo').html(_.template(tplS)({obj:siteInfo}));
        },  

        getPostData : function() {
             var dom = $('#'+mId);
             tempOpt.engine = dom.find('.selectInfo').find('select').val();
             if (tempOpt.engine == '0') { tempOpt.engine = ''};
             tempOpt.end_date = dom.find('.to_time').val();
             tempOpt.begin_date = dom.find('.from_time').val();
             tempOpt.page = 1;

             if (tempOpt.end_date == '' || tempOpt.begin_date == '') {
                 alert('The time is required!');
                 return false;
             }
             if (new Date(tempOpt.end_date) < new Date(tempOpt.begin_date)) {
                 alert('The end time is less than the start time!');
                 return false;
             }
             if (new Date(tempOpt.end_date) > new Date()) {
                 alert('The end time is greater than the current time!');
                 return false;
             }
             return tempOpt;
        }, 

        fetchDataUserEmail : function(data) {
             var tthis = this,
                ajaxOpt = {
                    url : seajs.data.vars.apiUrl+'email_status_site_user',
                    type : 'POST',
                    data : data,
                    success : function(data) {       
                        console.log(data); 
                        tthis.fetchDataUserEmailSuccess(data);          
                    },
                    error : function(xhr, errorType, error) {
                    },
                    complete : function(xhr,status){
                        share.load($('#'+mId),false); 
                    }
                };

            share.load($('#'+mId),true);
            share.ajax(ajaxOpt,true);
        },

        fetchDataUserEmailSuccess : function(data) {
            if (parseInt(data.total) > 0) {
                var html = '';
                    _.each(data.data,function(obj,num){
                        html += "<div><span>"+(num+1)+": </span>"+obj.ORIG_SUBJECT+"</div>";
                    });
                this.openDialog(html);
            } 
        },

        fetchData : function(data) {
            var tthis = this,
                ajaxOpt = {
                url : seajs.data.vars.apiUrl+'email_status_site',
                type : 'POST',
                data : data,
                success : function(data) {       
                    //console.log(data);           
                    tthis.fetchSuccess(data);
                    tthis.pagination(data);
                },
                error : function(xhr, errorType, error) {
                },
                complete : function(xhr,status){
                    share.load($('#'+mId),false); 
                }
            };

            share.load($('#'+mId),true); 
            share.ajax(ajaxOpt,true);
        },

        pagination : function(data) {
            var tthis = this;
            new $.fn.pagination({
                dom : $('#'+mId).find(".pagination"),
                total_num : parseInt(data.total), 
                num_edge_entries: 1, 
                current_page:tempOpt.page,
                num_display_entries: 4, 
                items_per_page:tempOpt.offset,
                callback : function(current){
                    tempOpt.page = current;
                    tthis.fetchData(tempOpt);
                }
            });
        },

        fetchSuccess : function(data) {
            //add main gold
            this.details(data);
        },

        details : function(data) {
            var arr = [];
            arr.push({name:'Project',val:'NAME'});
            arr.push({name:'User ID',val:'REPORT_USR_ID',href:true});
            arr.push({name:'Report number ',val:'MESSAGE_CNT'});
            arr.push({name:'Report detail ',text:'check email title'});

            var total = {};
                total.BEING_DATE = tempOpt.begin_date;
                total.END_DATE = tempOpt.end_date;
                total.SITE = share.getSiteName(tempOpt.engine);
                total.MES_TATOL =  data.total_msg_cnt ? Number(data.total_msg_cnt) : 0;
                total.USER_TATOL = data.total ? Number(data.total) : 0;

            $('#'+mId).find('.desc').html(_.template(tplD)({obj:total}));
            $('#'+mId).find('.table').html(_.template(tplT)({obj:data.data,arr:arr}));
        }

    });
    module.exports = AOLSpamBSView;
});


